"""
Written by Noah Krach: Contact at noah.krach1@gmail.com if you have any questions

Takes an already created fishnet and performs a spatial join by counting how many of the interested features fall
in each cell and then add that value to the fishnets attribute table.

The path to the fishnet must be changed to the location where the original fishnet from the dataverse is saved.
This fishnet will have a new field called count added that will hold the results of this code. Make sure to rename
the fishnet appropriately. 
"""
import arcpy

#allows for overwriting of existing files
arcpy.env.overwriteOutput = True

#the path to the fishnet that will be used
#THIS PATH MUST BE CHANGED
##############################################################################################################
fishnet = "C:\\Path\\To\\Fishnet\\Fishnet.shp"
##############################################################################################################

#adds a field to the fishnet called "Count"
arcpy.AddField_management(fishnet, "Count", "DOUBLE")

#path to the layer that will be counted
#THIS PATH MUST BE CHANGED
#############################################################################################################
join_layer = "C:\\Path\\To\\Feature\\Of\Interest\\Bathy_Points.shp"
#############################################################################################################

#makes a feature layer out of the layer that will be counted
arcpy.MakeFeatureLayer_management(join_layer, "join_layer")

#for every cell in the fishnet, this code will be executed
for row in arcpy.da.SearchCursor(fishnet, "FID"):

    #a feature layer will be made of an individual cell
    arcpy.MakeFeatureLayer_management(fishnet, "row_layer", "FID = {0}".format(row[0])) 

    #A selection will be made on all the points that intersect the individual cell
    arcpy.SelectLayerByLocation_management("join_layer", "INTERSECT", "row_layer")

    #the selection has been made. This returns the count of how many points were selected
    result = arcpy.GetCount_management("join_layer")
    count = int(result.getOutput(0))
    print count

    #Updates the field "Count" that was created earlier with the returned count
    with arcpy.da.UpdateCursor(fishnet, "Count", "FID = {0}".format(row[0])) as cursor:
        for x in cursor:
            x[0] = count
            cursor.updateRow(x)

    print "Row complete: " + str(row[0])


       
